<!--
    在init方法里面填上url连上后端应该就可以跑了
-->

<template>
  <div class="app-container">
    <el-card class="card-box">
      <div style="height: 580px; width: 100%">
        <div class="flexDiv">
          <div class="card-title">当前查询:{{ from }} {{ typeName }}(一周内数据)</div>
        </div>
        <div class="flexDiv">
          <div class="card-title">{{ name }}</div>
          <div>
            <el-button type="text" icon="el-icon-close" style="color: black" @click="goback" />
          </div>
        </div>

        <div v-show="!showAll" class="card-content" style="display: flex">
          <div class="card-left">
            <div class="title">
              <div class="title-name">时间排序:</div>
            </div>
            <el-table
              id="tableBox"
              :data="detailData"
              style="width: 100%"
              class="tableBox"
              max-height="450"
              :row-class-name="tableRowClassName"
              @row-click="handleClickChange"
            >
              <el-table-column label="序号" prop="index" width="55" align="center">
                <template slot-scope="scope">
                  <span>{{ scope.$index + 1 }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="deviceTime" label="具体时间" width="200" align="center" />
              <el-table-column prop="doserate" :label="labelName" align="center">
                <template slot-scope="scope">
                  <div
                    v-if="scope.row.doserate > levelOne &&
                      scope.row.doserate < levelTwo
                      ? true
                      : false
                    "
                    style="color: #e19b16"
                  >
                    {{ scope.row.doserate }} {{ updateLabel }}
                  </div>
                  <div v-else-if="scope.row.doserate > levelTwo ? true : false" style="color: #e84b3f">
                    {{ scope.row.doserate }} {{ updateLabel }}
                  </div>
                  <div v-else>{{ scope.row.doserate }} {{ updateLabel }}</div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="card-right">
            <div class="title-name">趋势图:</div>

            <div id="mychart" class="echart" :style="myChartStyle" />

            <div class="data-analyse">
              <div class="analyse-itemlist">
                <div class="analyse-item">
                  <a>获取量：{{ dataNumber }}个</a>
                </div>
                <div class="analyse-item">
                  <a>最大值：{{ dataMax }}{{ updateLabel }}</a>
                </div>
                <div class="analyse-item">
                  <a>平均值：{{ dataAvg }}{{ updateLabel }}</a>
                </div>
                <div class="analyse-item">
                  <a>最小值：{{ dataMin }}{{ updateLabel }}</a>
                </div>
                <div class="analyse-item">
                  <a>{{ dateMax }}</a>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div v-show="showAll" class="card-content1">
          <div class="title">
            <div class="title-name">报表详情:</div>
          </div>
          <div style="display: flex">
            <div class="card-table">
              <el-table :data="detailData2" style="width: 98%" class="tableBox" stripe max-height="400">
                <el-table-column label="序号" prop="index" width="55">
                  <template slot-scope="scope">
                    <span>{{ scope.$index + 1 }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="deviceTime" label="具体时间" width="200" align="center" />
                <el-table-column prop="stationName" label="站点名称" align="center" />
                <el-table-column prop="sysName" label="设备名称" align="center" />
                <el-table-column prop="doserate" :label="labelName" align="center">
                  <template slot-scope="scope">
                    <div
                      v-if="scope.row.doserate > levelOne &&
                        scope.row.doserate < levelTwo
                        ? true
                        : false
                      "
                      style="color: #e19b16"
                    >
                      {{ scope.row.doserate }} {{ updateLabel }}
                    </div>
                    <div v-else-if="scope.row.doserate > levelTwo ? true : false" style="color: #e84b3f">
                      {{ scope.row.doserate }} {{ updateLabel }}
                    </div>
                    <div v-else>{{ scope.row.doserate }} {{ updateLabel }}</div>
                  </template>
                </el-table-column>
                <el-table-column label="检测状态" prop="status" align="center">
                  <template>
                    <div style="display: flex; justify-content: center">
                      <div
                        :class="status === '正常'
                          ? 'zc'
                          : status === '一级报警'
                            ? 'yjbj'
                            : status === '二级报警'
                              ? 'ejbj'
                              : 'lx'
                        "
                      />
                      <div>{{ status }}</div>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
              <pagination
                v-show="total > 0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getDataList"
              />
              <div style="display: flex; justify-content: space-around">
                <div style="width: 370px; height: 50px">
                  <pagination
                    v-show="total > 0"
                    :total="total"
                    :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize"
                    layout="total, prev, pager, next"
                    pager-count="3"
                    hide-on-single-page
                    style="margin: 0px"
                    @pagination="getDataList"
                  />
                </div>
                <el-button type="primary" style="margin: auto; margin-left: 400px">导出</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  data() {
    return {
      detailData: [
        {
          deviceTime: '2024-05-18',
          doserate: '12.9'
        },
        {
          deviceTime: '2024-05-19',
          doserate: '15.9'
        },
        {
          deviceTime: '2024-05-20',
          doserate: '15.9'
        },
        {
          deviceTime: '2024-05-21',
          doserate: '30.9'
        },
        {
          deviceTime: '2024-05-22',
          doserate: '35.9'
        },
        {
          deviceTime: '2024-05-23',
          doserate: '32.9'
        },
        {
          deviceTime: '2024-05-24',
          doserate: '38.9'
        }
      ],
      type: '',
      typeName: '',
      detailData2: [],
      chartData: [],
      chartData2: [],
      // 其他信息
      dataAvg: '',
      dateMax: '', // 分之十克
      dataMax: '', // 平均值
      dataMin: '', // 最小值
      dataNumber: '', //
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      status: '',
      levelOne: '',
      levelTwo: '',
      temprow: '',
      myChart: {},
      xData: [], // 横坐标
      yData: [], // 数据
      myChartStyle: { float: 'left', width: '100%', height: '400px' }, // 图表样式
      warn: { warn1: 1, warn2: 2 },
      showAll: 0,
      typeNames: [
        { typeId: 'all', typeName: '全部数据' },
        { typeId: 'temperature', typeName: '温度检测', unit: '°C' },
        { typeId: 'humidity', typeName: '湿度检测', unit: '%' },
        { typeId: 'noiseLevel', typeName: '噪音水平', unit: 'dB' },
        { typeId: 'airPressure', typeName: '气压', unit: 'hPa' },
        { typeId: 'windSpeed', typeName: '风速', unit: 'm/s' },
        { typeId: 'airQualityIndex', typeName: '空气质量指数', unit: 'AQI' }
      ],
      from: ''
    }
  },
  computed: {
    updateLabel() { // 返回一个单位
      const typeIdOneValues = this.typeNames
        .filter(item => item.typeId === this.type) // 过滤出 typeId 为 1 的对象
      console.log(typeIdOneValues[0].typeName)
      return typeIdOneValues[0].unit
    },
    labelName() {
      const typeIdOneValues = this.typeNames
        .filter(item => item.typeId === this.type) // 过滤出 typeId 为 1 的对象
      console.log(typeIdOneValues[0].typeName)
      return typeIdOneValues[0].typeName
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      // 初始化，从后端那到历史采集数据，是一个 日期deviceTime 和 采集量doserate 组成的类数组
      // 得到的数据直接放进detailData中应该一切都可以了
      var id = this.$route.query.id
      this.type = this.$route.query.typeName
      this.from = this.$route.query.from
      this.axios({
        method: 'get',
        url: 'http://139.9.77.245:8081/environment-data/' + id
      }).then(response => { // 使用箭头函数
        const ret = response.data
        var result = response.data
        if (result.code === 0) {
          console.log(ret)
          this.detailData = result.data

          this.getthresholds()
        } else {
          console.log('请求数据失败')
        }
      })
    },
    getthresholds() {
      // 获取阈值
      this.axios({
        method: 'get',
        url: 'http://139.9.77.245:8081/thresholds/' + this.type
      }).then(response => { // 使用箭头函数
        const ret = response.data
        if (ret.code === 0) {
          console.log(ret)
          this.typeName = ret.data.name
          this.warn.warn1 = ret.data.warningThreshold
          this.warn.warn2 = ret.data.dangerThreshold
          this.levelOne = this.warn.warn1
          this.levelTwo = this.warn.warn2
          this.initEcharts()
        } else {
          console.log('信息获取失败')
          console.log(ret)
        }
      }).catch(error => {
        console.error('请求出错:', error)
      })
    },
    getDataList() {
    },
    initEcharts() {
      this.xData = this.detailData.map(item => item.deviceTime)
      this.xData = this.xData.reverse()
      this.yData = this.detailData.map(item => item.doserate)
      this.yData = this.yData.reverse()
      this.analyseData()
      var yAxisMax = Math.max(this.warn.warn2, this.dataMax)
      yAxisMax = Math.ceil(yAxisMax / 10) * 10
      console.log(yAxisMax)
      const option = {
        title: {
          text: '',
          left: '1%'
        },
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          left: '5%',
          right: '15%',
          bottom: '10%'
        },

        xAxis: {
          data: this.xData
        },
        yAxis: {
          max: yAxisMax
        },
        series: [
          {
            name: this.labelName,
            data: this.yData.map(item => {
              if (item > this.warm) {
                return {
                  value: item,
                  itemStyle: {
                    color: '#F33'
                  }
                }
              }
              return item
            }),
            type: 'line', // 类型设置为折线图
            markLine: {
              symbol: ['none', 'none'], // 去掉箭头
              label: {
                position: 'insideEndTop',
                distance: [-65, -8] // 文字在标线处的位置
              },
              data: [
                {
                  name: '阈值1',
                  yAxis: this.warn.warn1,
                  label: {
                    formatter: '警告阈值:' + this.warn.warn1
                  }
                },
                {
                  name: '阈值2',
                  yAxis: Math.min(this.warn.warn2, yAxisMax),
                  label: {
                    formatter: '危险阈值:' + this.warn.warn2
                  }
                }
              ],
              lineStyle: {
                color: '#f00'
              }
            }
          }
        ]
      }
      // console.log(option)
      var chartDom = document.getElementById('mychart')
      var myChart = this.$echarts.init(chartDom)

      option && myChart.setOption(option)
      // 图形和表格联动
      // 移入该区域时，高亮
      var self = this
      myChart.on('click', function(params) {
        self.temprow = self.yData.length - params.dataIndex - 1
      })
      this.myChart = echarts.init(document.getElementById('mychart'))
      this.myChart.setOption(option)
      // 随着屏幕大小调节图表
      window.addEventListener('resize', () => {
        this.myChart.resize()
      })
    },
    analyseData() {
      // 分析数据，提取数据的均值、最大值、最小值、平均值、分值
      this.dataNumber = this.yData.length
      this.dataMax = -Infinity // 设置初始最大值为负无穷
      this.dataMin = Infinity // 设置初始最小值为正无穷
      this.dataAvg = 0 // 初始化平均值为0
      this.dataNumber = this.yData.length
      for (var i = 0; i < this.yData.length; i++) {
        this.dataMax = Math.max(this.dataMax, parseFloat(this.yData[i]))
        this.dataMin = Math.min(this.dataMin, parseFloat(this.yData[i]))
        this.dataAvg += parseFloat(this.yData[i])
        // console.log(this.dataAvg)
      }
      this.dataAvg /= this.dataNumber
      this.dataAvg = this.dataAvg.toFixed(2) // 保留两位小数
    },
    handleClickChange(row, event, column) {
      console.log(this.yData.length - row.index)
      this.temprow = row.index
      this.myChart.dispatchAction({
        type: 'showTip',
        seriesIndex: 0,
        dataIndex: this.yData.length - row.index - 1
      })
    },
    tableRowClassName({ row, rowIndex }) {
      // console.log(rowIndex)
      // 把每一行的索引放进row
      row.index = rowIndex
      // if (row.active == true) {
      if (rowIndex == this.temprow) {
        return 'light-row'
      }
    },
    goback() {
      this.$router.go(-1)
    }

  }
}
</script>

<style scoped lang="scss">
.card-content1 {
  height: 460px;

  // display: flex;
  .card-table {
    width: 75%;
    height: 400px;
  }

  .card-left {
    width: 23%;

    .left-detail {
      height: 270px;
      font-size: 14px;
      width: 260px;
      padding: 20px 0px 10px 10px;
      // background-color: rgb(116, 75, 75);
      border: 1px solid #cacaca;
    }
  }
}

// title
.title {
  height: 40px;
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  font-weight: bold;
  padding: 4px 10px 20px 10px;

  .title-name {
    width: 80px;
  }

  .title-refresh {
    width: 70px;
    color: #1890ff;
    text-align: right;
    padding-right: 15px;
  }
}

.right-title {
  height: 40px;
  font-size: 14px;
  margin-left: 40px;
}

// el-form
::v-deep .el-form {
  height: 55px;
  padding: 10px;

  .el-form-item__label {
    font-size: 14px;
    font-weight: bold;
    color: black;
  }
}

// ::v-deep .el-input__inner {
//   width: 200px;
//   height: 28px;
//   font-size: 14px;
// }
.el-button {
  height: 28px;
  width: 64px;
  font-size: 14px;
  line-height: 5px;
}

.red {
  color: red;
}

.green {
  color: green;
}

.card-box {
  padding: 0px;
  // margin-bottom: 20px;
}

// right-left
.card-left {
  width: 40%;
  height: 600px;
  // background-color: rgb(124, 66, 66);
}

.card-right {
  // width: 800px;
  width: 60%;
  height: 580px;

  // padding-left: 40px;
  // background-color: rgb(159, 216, 127);
  .title-name {
    margin-left: 20px;
    width: 80px;
    font-size: 14px;
    font-weight: bold;
  }

  .data-analyse {
    margin: 10px;
    height: 100px;
    width: 300px;

    .analyse-title {
      height: 50px;
      padding: 10px 10px 0px 10px;
      font-weight: bold;
      font-size: 14px;
    }

    .analyse-itemlist {
      height: 60px;
      width: 600px;
      margin-left: 50px;
      font-size: 14px;
      display: flex;
      flex-wrap: wrap;
    }

    .analyse-item {
      min-width: 300px;
      height: 30px;
      margin: 0px;
      padding: 0px;
    }
  }
}

.card-title {
  padding-left: 10px;
  margin: 6px 0px;
  font-size: 16px;
  font-weight: bold;
}

// table
::v-deep .el-table {
  height: 460px;
  border: 0;
  padding-left: 10px;

  .el-table__header tr,
  .el-table__header th {
    height: 36px;
    color: black;
    font-size: 14px;
  }

  .el-table__body tr,
  .el-table__body td {
    height: 36px !important;
  }

  // 修改行高
  .cell {
    line-height: 20px;
  }

  .light-row {
    background: #f5f7fa;
  }
}

// 检测状态
.zc {
  height: 7px;
  width: 7px;
  border-radius: 50%;
  background-color: green;
  margin: auto 9px;
}

.yjbj {
  height: 7px;
  width: 7px;
  border-radius: 50%;
  background-color: #e19b16;
  margin: auto 9px;
}

.ejbj {
  height: 7px;
  width: 7px;
  border-radius: 50%;
  background-color: #e84b3f;
  margin: auto 9px;
}

.lx {
  height: 7px;
  width: 7px;
  border-radius: 50%;
  background-color: gray;
  margin: auto 9px;
}

.zc-t {
  color: green;
}

.yjbj-t {
  color: #e19b16;
}

.ejbj-t {
  color: #e84b3f;
}

.lx-t {
  color: gray;
}

.flexDiv {
  display: flex;
  justify-content: space-between;
}
</style>
